package com.yilin.gateway.config;

import com.yilin.gateway.filter_factory.ZuulGatewayFilterFactory;
import com.yilin.gateway.filter_factory.DecryptRequestBodyGatewayFilterFactory;
import com.yilin.gateway.filter_factory.EncryptResponseBodyGatewayFilterFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GatewayConfig {

    /**
     * 注入自定义授权网关过滤器工厂
     */
    @Bean
    public ZuulGatewayFilterFactory authGatewayFilterFactory() {
        return new ZuulGatewayFilterFactory();
    }

    /**
     * request body解密
     */
    @Bean
    public DecryptRequestBodyGatewayFilterFactory decryptRequestBodyGatewayFilterFactory() {
        return new DecryptRequestBodyGatewayFilterFactory();
    }

    /**
     * response body 加密
     */
    @Bean
    public EncryptResponseBodyGatewayFilterFactory encryptResponseBodyGatewayFilterFactory() {
        return new EncryptResponseBodyGatewayFilterFactory();
    }


    @Bean
    public CorsFilter corsFilter() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("*");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
//    //等保要求
//    @Bean
//    public CorsFilter customCorsFilter() {
//        CorsConfiguration config = new CorsConfiguration();
//        if(specificDomainName==null){
//            config.addAllowedOrigin("*"); // 只允许特定域名
//        }else{
//            String[] strings=specificDomainName.split(",");
//            for (String url:strings ) {
//                config.addAllowedOrigin(url); // 只允许特定域名
//            }
//        }
//        config.setAllowCredentials(false); // 禁用授权凭证
//        config.addAllowedMethod("*");
//        config.addAllowedHeader("*");
//        config.addExposedHeader("*");
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/user/login/passLogin", config); // 配置只应用于这个路径
//        return new CorsFilter(source);
//    }
}
